<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <!-- 加上外层的form标签，会在移动端键盘唤醒时，有一个搜索按钮 如果没有form这个标签就没有搜索按钮 -->
    <!-- show-action 控制取消按钮显示隐藏 cancel 取消按钮的触发事件 -->
    <!-- search搜索内容点击搜索或者键盘回车触发的事件 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
         background="#3296fa"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <SearchResults
     :searchText="searchText"
     v-if="isResultShow"></SearchResults>
    <!-- 提示内容 -->
    <SearchSuggestion
     v-else-if="searchText"
     @search="onSearch"
     :searchText="searchText"></SearchSuggestion>
    <!-- 历史记录 -->
    <SearchHistory
    v-else
    @search="onSearch"
    :searchHistories="searchHistories"
    @clearSearchHistories="searchHistories = []"></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResults from './components/SearchResults.vue'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'searchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  },
  props: {},
  data() {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  computed: {},
  watch: {
    searchHistories: {
      handler(value) {
        setItem('TOUTIAO_SEARCH_HISTORIES', value)
      }
    }
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      // console.log(val)
      // 更新文本框内容
      this.searchText = val
      // 渲染搜索结果
      this.isResultShow = true
      // 存储搜索历史记录  [LRU 缓存]
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
    },
    onCancel() {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
